<?php

namespace app\api\service;
use app\api\model\xyb\AgentAddress;
use app\api\model\xyb\AgentAddressGroup;
use app\api\model\xyb\UserReceiveApply;
use app\api\model\xyb\Wallets;
use app\common\controller\Api;
use app\common\model\Circle;
use app\common\model\circle\User as CircleUser;
use app\common\model\User;
use app\common\model\xyb\AdminBelong;
use \app\common\model\User as UsersModel;
use app\common\model\xyb\UserBelong;
use think\Request;

class UsersService{


    public static function getAuthUsers(){
//      $user_id = request()->header('user-id', 2);
//      return UsersModel::get($user_id);
        return (new Api())->auth->getUser();
    }

    /*获取用户所在是社群是否开通服务；用户是否可以申请接单员*/
    public static function getCommunityWhereUsersLocated($users_id = 0){
        /*获取用户所在的社群*/
        if(!$circle_id = User::where('id', $users_id)->value('circle_id')){
            return false;
        }
        if(!$user_circle = self::getUserCircleInfo($users_id, $circle_id)){
            return false;
        }
        if(!$circle_name = $user_circle->circle_info->name){
            return false;
        }
        /*获取用户所在圈子开通的系统*/
        $agent_info = AdminBelong::where(['agent_area' => $circle_name])->find();
        if(!$agent_info){
            return false;
        }
        /*用户所在的圈子*/
        $agent_info->agent_id = $agent_info->admin_id;
        $agent_info->agent_name = $circle_name;

        /*用户所在代理校区的身份；1:普通用户；2：跑腿员；3：代理；4：跑腿员加代理*/
        $agent_info->users_identity = 1;
        $agent_info->is_rider = false;
        $agent_info->is_rider_receiving = false;
        $agent_info->is_rider_stated = false;
        $agent_info->is_agent = false;
        $agent_info->rider_info = (new \ArrayObject());
        $users_identity = UserBelong::where('user_id',$users_id)->where('default_agent_id', $agent_info->agent_id)
            ->value('xyb_group_id');

        $agent_info->xyb_group_id = $users_identity?$users_identity:1;
        if($users_identity == '2'){
            /*获取用户跑腿信息*/
            $agent_info->users_identity = 2;
            $agent_info->rider_info = UserReceiveApply::where('user_id', $users_id)
                ->where('agent_id', $agent_info->agent_id)->where('status', 1)->find();
            if($agent_info->rider_info){
                $agent_info->is_rider = true;
                $agent_info->is_rider_stated = (int)$agent_info->rider_info->stated === 1;
                if($agent_info->is_rider_stated){
                    $agent_info->is_rider_receiving = (int)$agent_info->rider_info->presence === 1;
                }
            }
        }
        elseif ( $users_identity == '3' ){
            if($agent_info->bind_agent_user_id == $users_id){
                $agent_info->users_identity = 3;
                $agent_info->is_agent = true;
            }
        }
        elseif ( $users_identity == '2,3'){ //跑腿员
            /*判断当前圈子绑定的代理ID是否是当前用户*/
            if($agent_info->bind_agent_user_id == $users_id){
                $agent_info->users_identity = 4;
                $agent_info->is_agent = true;
            }
            $agent_info->rider_info = UserReceiveApply::where('user_id', $users_id)
                ->where('agent_id', $agent_info->agent_id)->where('status', 1)->find();
            if($agent_info->rider_info){
                $agent_info->is_rider = true;
                $agent_info->is_rider_stated = (int)$agent_info->rider_info->stated === 1;
                if($agent_info->is_rider_stated){
                    $agent_info->is_rider_receiving = (int)$agent_info->rider_info->presence === 1;
                }
            }
        }else {
            $agent_info->users_identity = 1;
            $agent_info->is_rider = false;
            $agent_info->is_agent = false;
        }
        return $agent_info;
    }

    /*获取用户所在是社群是否开通服务；用户是否可以申请接单员*/
    public static function getIndexCommunityWhereUsersLocated($users_id = 0,$circle_id = 0){

        if(!$user_circle = self::getUserCircleInfo($users_id, $circle_id)){
            return false;
        }
        if(!$circle_name = $user_circle->circle_info->name){
            return false;
        }
        /*获取用户所在圈子开通的系统*/
        $agent_info = AdminBelong::where(['agent_area' => $circle_name])->find();
        if(!$agent_info){
            return false;
        }
        /*用户所在的圈子*/
        $agent_info->agent_id = $agent_info->admin_id;

        /*用户所在代理校区的身份；1:普通用户；2：跑腿员；3：代理；4：跑腿员加代理*/
        $agent_info->users_identity = 1;
        $agent_info->is_rider = false;
        $agent_info->is_rider_receiving = false;
        $agent_info->is_rider_stated = false;
        $agent_info->is_agent = false;
        $agent_info->rider_info = (new \ArrayObject());
        $users_identity = UserBelong::where('user_id',$users_id)->where('default_agent_id', $agent_info->agent_id)
            ->value('xyb_group_id');

        $agent_info->xyb_group_id = $users_identity?$users_identity:1;
        if($users_identity == '2'){
            /*获取用户跑腿信息*/
            $agent_info->users_identity = 2;
            $agent_info->rider_info = UserReceiveApply::where('user_id', $users_id)
                ->where('agent_id', $agent_info->agent_id)->where('status', 1)->find();
            if($agent_info->rider_info){
                $agent_info->is_rider = true;
                $agent_info->is_rider_stated = (int)$agent_info->rider_info->stated === 1;
                if($agent_info->is_rider_stated){
                    $agent_info->is_rider_receiving = (int)$agent_info->rider_info->presence === 1;
                }
            }
        }
        elseif ( $users_identity == '3' ){
            if($agent_info->bind_agent_user_id == $users_id){
                $agent_info->users_identity = 3;
                $agent_info->is_agent = true;
            }
        }
        elseif ( $users_identity == '2,3'){ //跑腿员
            /*判断当前圈子绑定的代理ID是否是当前用户*/
            if($agent_info->bind_agent_user_id == $users_id){
                $agent_info->users_identity = 4;
                $agent_info->is_agent = true;
            }
            $agent_info->rider_info = UserReceiveApply::where('user_id', $users_id)
                ->where('agent_id', $agent_info->agent_id)->where('status', 1)->find();
            if($agent_info->rider_info){
                $agent_info->is_rider = true;
                $agent_info->is_rider_stated = (int)$agent_info->rider_info->stated === 1;
                if($agent_info->is_rider_stated){
                    $agent_info->is_rider_receiving = (int)$agent_info->rider_info->presence === 1;
                }
            }
        }else {
            $agent_info->users_identity = 1;
            $agent_info->is_rider = false;
            $agent_info->is_agent = false;
        }
        return $agent_info;
    }
    public static function getProxyBoundToUserId(int $users_id = 0){

        $agent_info = (new AdminBelong())->where('bind_agent_user_id',$users_id)->find();
        if(!$agent_info){
            return false;
        }
        return (int)$agent_info->admin_id;
    }


    /*获取用户地址信息*/
    public static function getUsersCommunityAddressInformation($users_id, $agent_id = 0){
        $agent_info = self::getCommunityWhereUsersLocated($users_id);
        /*获取分组*/
        $condition = [
            'agent_id'      => $agent_info->agent_id,
            'status'        => 'normal'
        ];
        $address_group = AgentAddressGroup::field('id,name')->where($condition)->select();
        /*获取地址*/
        foreach ($address_group as $key => $value){
            $condition = ['group_id' => $value['id'], 'status' => 'normal'];
            $address_group[$key]['children'] = AgentAddress::field('id,name')->where($condition)->select();
        }
        return $address_group;
    }

    /*获取用户圈子信息*/
    public static function getUserCircleInfo($users_id, $circle_id){
        $user_circle_id = 0;
        if($circle_id && $circle_id > 0){
            $where = ['user_id' => $users_id, 'is_auth' => 1, 'circle_id' => $circle_id];
            $field = 'id,circle_id,identity,is_auth,user_id';
            $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
            if(!$user_circle_relation){
                return false;
            }
            $user_circle_id = (int)$user_circle_relation->circle_id;
        } else {
            $where = ['user_id'=> $users_id,'is_auth' => 1,'circle_id' => ['>', 1]];
            $field = 'id,circle_id,identity,is_auth,user_id';
            $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
            if(!$user_circle_relation){
                return false;
            }
            $user_circle_id = (int)$user_circle_relation->circle_id;
        }
        if(!$user_circle_id){
            return false;
        }
        $field = 'id,name,address,logo_image,image';
        $where = ['id' =>$user_circle_id,'status'=> 2];
        if(! $circle = Circle::field($field)->where($where)->find()){
            return false;
        }
        $user_circle_relation->circle_info = $circle;
        return $user_circle_relation;
    }

    /*获取用户圈子信息*/
    public static function getUsersCircleId($users_id, $circle_id){
        $user_circle_id = 0;
        if($circle_id && $circle_id > 0){
            $where = ['user_id' => $users_id, 'is_auth' => 1, 'circle_id' => $circle_id];
            $field = 'id,circle_id,identity,is_auth,user_id';
            $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
            if(!$user_circle_relation){
                return $user_circle_id;
            }
            $user_circle_id = (int)$user_circle_relation->circle_id;
        } else {
            $where = ['user_id'=> $users_id,'is_auth' => 1,'circle_id' => ['>', 1]];
            $field = 'id,circle_id,identity,is_auth,user_id';
            $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
            if(!$user_circle_relation){
                return $user_circle_id;
            }
            $user_circle_id = (int)$user_circle_relation->circle_id;
        }
        if(!$user_circle_id){
            return $user_circle_id;
        }
        $field = 'id,name,address,logo_image,image';
        $where = ['id' =>$user_circle_id,'status'=> 2];
        if(!$circle = Circle::field($field)->where($where)->find()){
            return $user_circle_id;
        }
        return $user_circle_id;
    }

    public static function formatUsersCircleStatusInfo($users_id, $circle_id){
        $response = ['circle_id' => 0, 'join_status' => false, 'pins'=>false];
        /*用户圈子信息*/

        if($circle_id && $circle_id > 0){
            $where = ['user_id' => $users_id, 'is_auth' => 1, 'circle_id' => $circle_id];
            $field = 'id,circle_id,identity,is_auth,user_id';
            $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
            /*用户所在当前圈子*/
            if($user_circle_relation){
                $response['circle_id'] = $user_circle_relation->circle_id;
                $response['join_status'] = true; //是否加入圈子
                $response['pins'] = false;
//                $response['circle_id'] = $circle_id;
//                $response['join_status'] = false; //是否加入圈子
//                $response['pins'] = true;
                return $response;
            }
        }
        /*获取用户最后一次加入的圈子*/
        $where = ['user_id'=> $users_id,'is_auth' => 1,'circle_id' => ['>', 1]];
        $field = 'id,circle_id,identity,is_auth,user_id';
        $user_circle_relation = CircleUser::field($field)->where($where)->order('id desc')->find();
        if($user_circle_relation){
            $response['circle_id'] = (int)$user_circle_relation->circle_id;
            $response['join_status'] = true; //是否加入圈子
            $response['pins'] = false;
//            $response['circle_id'] = 0;
//            $response['join_status'] = false; //是否加入圈子
//            $response['pins'] = true;
        }
        return $response;
    }

    /*获取用户基础信息；包含头像，昵称*/
    public static function getUsersFoundation($users_id)
    {
        /*查询用户信息*/
        $field = 'id,nickname,avatar,unionid,openid,miniapp_openid';
        $users = UsersModel::field($field)->where('id', $users_id)->find();
        return [
            'nickname'      => $users?$users->nickname:'',
            'avatar'        => $users?$users->avatar:'',
            'openid'        => $users?$users->miniapp_openid:'',
        ];
    }

    public static function getReceivingUsersFoundation($users_id, $agent_id){
        /*查询用户信息*/
        $field = 'id,nickname,avatar,unionid,openid,miniapp_openid';
        $users = UsersModel::field($field)->where('id', $users_id)->find();
        $field = 'id,agent_id,life_image,status,mobile,evaluate';
        $users_receive = UserReceiveApply::field($field)->where('user_id', $users_id)->where('agent_id', $agent_id)->find();
        return [
            'nickname'      => isset($users->nickname)?$users->nickname:'',
            'avatar'        =>  isset($users->avatar)?$users->avatar:'',
            'openid'        =>  isset($users->miniapp_openid)?$users->miniapp_openid:'',
            'mobile'        =>  isset($users_receive->mobile)?$users_receive->mobile:'',
            'evaluate'        =>  isset($users_receive->evaluate)?$users_receive->evaluate:5
        ];
    }

    public static function setRiderOrderReceivingStatus($agent_id, $user_id){
        $user_receive = UserReceiveApply::where('agent_id', $agent_id)->where('user_id', $user_id)->find();
        if(!$user_receive){
            return false;
        }
        $user_receive->presence = $user_receive->presence == 1?2:1;
        $user_receive->updatetime = time();
        $user_receive->save();
        return $user_receive->presence;
    }

    public static function getRiderOrderReceivingStatus($agent_id, $user_id){
        $user_receive = UserReceiveApply::where('agent_id', $agent_id)->where('user_id', $user_id)->find();
        if(!$user_receive){
            return false;
        }
        return ((int)$user_receive->presence) === 1;
    }

    public static function getRiderIdleUsersLists($agent_id){
        $param = Request::instance()->param();
        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $field = 'yx_xyb_user_receive_apply.id,yx_xyb_user_receive_apply.user_id,yx_xyb_user_receive_apply.name,
        yx_xyb_user_receive_apply.mobile,yx_xyb_user_receive_apply.life_image,yx_xyb_user_receive_apply.presence';

        $count = UserReceiveApply::join('xyb_order', 'xyb_order.receive_id=yx_xyb_user_receive_apply.user_id')
            ->where('yx_xyb_user_receive_apply.agent_id', $agent_id)
            ->whereNotIn('xyb_order.status', ['2',  '8'])
            ->where('yx_xyb_user_receive_apply.status', '1')
            ->where('yx_xyb_user_receive_apply.stated', 1)
            ->where('yx_xyb_user_receive_apply.presence', 1)
            ->group('yx_xyb_user_receive_apply.user_id')
            ->count();

        $data = UserReceiveApply::field($field)
            ->join('xyb_order', 'xyb_order.receive_id=yx_xyb_user_receive_apply.user_id')
            ->where('yx_xyb_user_receive_apply.agent_id', $agent_id)
            ->whereNotIn('xyb_order.status', ['2', '8'])
            ->where('yx_xyb_user_receive_apply.status', '1')
            ->where('yx_xyb_user_receive_apply.presence', 1)
            ->where('yx_xyb_user_receive_apply.stated', 1)
            ->page($page,$limit)->group('yx_xyb_user_receive_apply.user_id')
            ->select();

        return ['total'=>$count, 'data'=>$data];

    }

    public static  function  alculateUserRevenue($identity, $user_id, $agent_id){
        $response = [
            'total_income'  => 0,
            'today_income'  => 0,
            'can_withdrawal_amount'=>0,
        ];
        if($identity == 1){
            return $response;
        }
        $walletsModel = new Wallets();
        $rider = [];
        $rider_walletsInfo = $walletsModel->where(['user_id'=>$user_id, 'type'=>'1'])->where('status', 'normal')->find();
        $agent_walletsInfo = $walletsModel->where(['user_id'=>$agent_id, 'type'=>'2'])->where('status', 'normal')->find();
        if($identity == 2){
            $rider = ProfitOrderService::calculateRiderIncome($user_id);
            $response['total_income'] = (float)$rider['total_income'];
            $response['today_income'] = (float)$rider['today_income'];
            $response['yesterday_income'] = (float)$rider['yesterday_income'];
            $response['seven_income'] = (float)$rider['seven_income'];
            $response['can_withdrawal_amount'] = (float)(isset($rider_walletsInfo['can_withdrawal_amount'])?$rider_walletsInfo['can_withdrawal_amount']:0);
            return $response;
        }
        $agent = [];
        if($identity == 3 ){
            $agent = ProfitOrderService::calculateAgentIncome($agent_id);
            $response['total_income'] = (float)$agent['total_income'];
            $response['today_income'] = (float)$agent['today_income'];
            $response['yesterday_income'] = (float)$agent['yesterday_income'];
            $response['seven_income'] = (float)$agent['seven_income'];
            $response['can_withdrawal_amount'] = (float)(isset($agent_walletsInfo['can_withdrawal_amount'])?(float)$agent_walletsInfo['can_withdrawal_amount']:0);
            return $response;
        }
        if($identity == 4 ){
            $rider = ProfitOrderService::calculateRiderIncome($user_id);
            $agent = ProfitOrderService::calculateAgentIncome($agent_id);
            $rider_withdrawal_amount = (float)(isset($rider_walletsInfo['can_withdrawal_amount'])?$rider_walletsInfo['can_withdrawal_amount']:0);
            $agent_withdrawal_amount = (float)(isset($agent_walletsInfo['can_withdrawal_amount'])?(float)$agent_walletsInfo['can_withdrawal_amount']:0);
            $response['total_income'] = (float)$rider['total_income'] + (float)$agent['total_income'];
            $response['today_income'] = (float)$rider['today_income'] + (float)$agent['today_income'];
            $response['yesterday_income'] = (float)$rider['yesterday_income'] + (float)$agent['yesterday_income'];
            $response['seven_income'] = (float)$rider['seven_income'] + (float)$agent['seven_income'];
            $response['can_withdrawal_amount'] = $rider_withdrawal_amount + $agent_withdrawal_amount;
        }
        $response['total_income'] = sprintf('%.2f', $response['total_income']);
        $response['today_income'] = sprintf('%.2f', $response['today_income']);
        $response['yesterday_income'] = sprintf('%.2f', $response['yesterday_income']);
        $response['seven_income'] = sprintf('%.2f', $response['seven_income']);
        $response['can_withdrawal_amount'] = sprintf('%.2f', $response['can_withdrawal_amount']);
//
//        $response['rider'] = $rider;
//        $response['agent'] = $agent;
        return $response;

    }

    public static  function  alculateUserWithdrawalRevenue($identity, $user_id, $agent_id){
        $response = [

            'total_withdrawal_amount'=>0,
            'rider_withdrawal_amount'=>0,
            'agent_withdrawal_amount'=>0,
        ];
        if($identity == 1){
            return $response;
        }
        $walletsModel = new Wallets();
        if($identity == 2){
            $walletsInfo = $walletsModel->where(['user_id'=>$user_id, 'type'=>'1'])->where('status', 'normal')->find();
            $response['total_withdrawal_amount'] = (float)(isset($walletsInfo['can_withdrawal_amount'])?$walletsInfo['can_withdrawal_amount']:0);
            $response['rider_withdrawal_amount'] = (float)(isset($walletsInfo['can_withdrawal_amount'])?$walletsInfo['can_withdrawal_amount']:0);
        }

        if($identity == 3){
            $walletsInfo = $walletsModel->where(['user_id'=>$agent_id, 'type'=>'2'])->where('status', 'normal')->find();
            $response['total_withdrawal_amount'] = (float)(isset($walletsInfo['can_withdrawal_amount'])?(float)$walletsInfo['can_withdrawal_amount']:0);
            $response['agent_withdrawal_amount'] = (float)(isset($walletsInfo['can_withdrawal_amount'])?(float)$walletsInfo['can_withdrawal_amount']:0);
        }

        if($identity == 4){
            $rider_walletsInfo = $walletsModel->where(['user_id'=>$user_id, 'type'=>'1'])->where('status', 'normal')->find();
            $agent_walletsInfo = $walletsModel->where(['user_id'=>$agent_id, 'type'=>'2'])->where('status', 'normal')->find();
            $rider_withdrawal_amount = (float)(isset($rider_walletsInfo['can_withdrawal_amount'])?$rider_walletsInfo['can_withdrawal_amount']:0);
            $agent_withdrawal_amount = (float)(isset($agent_walletsInfo['can_withdrawal_amount'])?(float)$agent_walletsInfo['can_withdrawal_amount']:0);
            $response['rider_withdrawal_amount'] = $rider_withdrawal_amount;
            $response['agent_withdrawal_amount'] = $agent_withdrawal_amount;
            $response['total_withdrawal_amount'] = $rider_withdrawal_amount + $agent_withdrawal_amount;
        }
//
//        $response['rider'] = $rider;
//        $response['agent'] = $agent;
        return $response;

    }

    public static function getUsersOpenId($user_id){
        return User::where('id', $user_id)->value('miniapp_openid');

    }

    public static function fadfads($users_id){
        if(!$circle_id = User::where('id', $users_id)->value('circle_id')){
            return false;
        }
        if(!$user_circle = self::getUserCircleInfo($users_id, $circle_id)){
            return false;
        }
        if(!$circle_name = $user_circle->circle_info->name){
            return false;
        }
        /*获取用户所在圈子开通的系统*/
        $agent_info = AdminBelong::where(['agent_area' => $circle_name])->find();
        if(!$agent_info){
            return false;
        }
        return $agent_info->admin_id;
    }

}